package com.ztf.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;

/**
 * @projectName: javabase
 * @package: com.ztf.jwt
 * @className: GenerateJwt
 * @author: kevin
 * @description: jwt生成与解密
 * @date: 2022/4/12 0012 10:50
 * @version: 1.0
 */
public class GenerateJwt {
    public static void main(String[] args) {
        GenerateJwt jwt = new GenerateJwt();
        String str =  jwt.generate();
        jwt.verifier(str);
    }

    /**
     * @param :
      * @return String
     * @author kevin
     * @description 加密
     * @date 2022/4/12 0012 11:05
     */
    public String generate(){
        HashMap<String,Object> map = new HashMap<>();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,20);
        String token = JWT.create()
                .withHeader(map) //可以不设定，就是使用默认的
                .withClaim("userId",20)//payload  //自定义用户名
                .withClaim("username","zhangsan")
                .withExpiresAt(instance.getTime()) //指定令牌过期时间
                .sign(Algorithm.HMAC256("fdahuifeuw78921"));//签名
        System.out.println("token"+token);
        return token;
    }

    /**
     * @param token:
      * @return String
     * @author kevin
     * @description 解密
     *
     * 页面解密
     *  var res = "tokeneyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDk3MzI3MjcsInVzZXJJZCI6MjAsInVzZXJuYW1lIjoiemhhbmdzYW4ifQ.rbrg1o6hOqwBmc8DqbeAbsKPXZiDO0HvsNSYqU7u-a8";
     *  var tokenStr= decodeURIComponent(escape(window.atob(res.split('.')[1])));
     * console.log(JSON.parse(tokenStr));
     * @date 2022/4/12 0012 11:05
     */
    public String verifier(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("fdahuifeuw78921")).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        decodedJWT.getClaim("userId").asInt();//获取负载里面对应的内容
        String username =  decodedJWT.getClaim("username").asString();
        decodedJWT.getExpiresAt();//获取过期时间
        System.out.println("username="+username);
        return username;
    }


}
